import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/auth.config';

export async function POST(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);
    console.log('Session:', JSON.stringify(session, null, 2));

    if (!session?.user?.id) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const { content } = await request.json();
    if (!content?.trim()) {
      return NextResponse.json({ error: '评论内容不能为空' }, { status: 400 });
    }

    // 先检查用户是否存在
    const user = await prisma.user.findUnique({
      where: { id: session.user.id }
    });

    console.log('Found user:', user);

    if (!user) {
      return NextResponse.json(
        { error: `用户不存在 (ID: ${session.user.id})` },
        { status: 404 }
      );
    }

    const comment = await prisma.comment.create({
      data: {
        content,
        trip: { connect: { id: params.id } },
        user: { connect: { id: user.id } }
      },
      include: {
        user: {
          select: { id: true, name: true }
        }
      }
    });

    return NextResponse.json(comment);
  } catch (error) {
    console.error('Create comment error:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : '评论失败' },
      { status: 500 }
    );
  }
}

export async function GET(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const comments = await prisma.comment.findMany({
      where: { tripId: params.id },
      include: {
        user: {
          select: { id: true, name: true }
        }
      },
      orderBy: { createdAt: 'desc' }
    });

    return NextResponse.json(comments);
  } catch (error) {
    console.error('Get comments error:', error);
    return NextResponse.json(
      { error: '获取评论失败' },
      { status: 500 }
    );
  }
} 